package org.pp.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class JwtUtil {
    private static final String secretKey="ppshop";
    private static final String claimBody="ppbody";

    /**
     * 生成Token  header.payload.sign
     *
     * //{"typ":"JWT","alg":"HS256"}
     */
    public static String createJwtToken(Map<String,Object> map, TimeUnit unit, long delay) {
        long expireTime = System.currentTimeMillis() + unit.toMillis(delay);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim(claimBody,map);
        return builder.withExpiresAt(new Date(expireTime))
                .sign(Algorithm.HMAC256(secretKey));
    }

    /**
     * 验证token的合法性
     */
    public static void verify(String token) {
        //这一行代码就可以起到验证的作用，因为在验证不匹配时它自动会抛出异常
        JWT.require(Algorithm.HMAC256(secretKey)).build().verify(token);
    }

    public static Map<String,Object> getPayload(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim(claimBody).asMap();
    }


   /* public static void main(String[] args) {
        Map<String,Object> mp= new ConcurrentHashMap<>();
        mp.put("uid",1L);
        String jwtToken = JwtUtil.createJwtToken(mp, TimeUnit.DAYS, 1);
        System.out.println(jwtToken);
        Map<String, Object> payload = getPayload(jwtToken);
        System.out.println(payload.getOrDefault("uid",""));
    }*/


}
